package sanger;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A simple utility class to wrap checks and other functionality for the
 * session class.
 * @author doskias
 */
public class Utilities {

    /**
     * Checks whether the client is logged in based on session information
     * @param session - the session object
     * @return true or false - depending on whether the user is logged or not.
     */
    public static boolean isLogged(HttpSession session) {
        if (session.getAttribute("auth") != null
                && session.getAttribute("auth").toString().equals("logged")) {
            return true;
        }
        return false;
    }

    /**
     *  Simple utility function used to redirect users who are not logged in.
     * @param session
     * @param request
     * @param response 
     */
    public static void logOrRedir(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        if (!Utilities.isLogged(session)) {
            try {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } catch (IOException ex) {
                Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    /**
     * Tries to authenticate a username/string tuple against the db of users
     * @param name - desired username
     * @param pass - desired password
     * @return - True on success or False otherwise
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public static boolean authenticate(String name, String pass) throws FileNotFoundException, IOException {

        String line;
        String[] tokens;
        BufferedReader bf = new BufferedReader(new FileReader(Constants.USER_FILE));

        while ((line = bf.readLine()) != null) {

            tokens = line.split(":");
            if (tokens[0].equals(name) && tokens[1].equals(pass)) {

                System.out.println("Successfully logged in");
                return true;
            }
        }

        return false;
    }

    public static Runnable Process(final String source, final String prefix, final String filename, final List<String> params) throws IOException, InterruptedException {
        return new Runnable() {

            public void run() {
                try {
                    if (!EC2Utilities.startInstance(0)) {
                        System.out.println("error starting the instance");
                        return;
                    }

                    if (!EC2Utilities.copyFileToEC2(source)) {
                        System.out.println("error copying file to EC2");
                        return;
                    }

                    if (!EC2Utilities.startRemoteProcess(prefix, filename, params)) {
                        System.out.println("error starting remote process");
                        return;
                    }
                } catch (IOException ex) {
                    System.out.println("Error while performing the job");
                    Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };



    }
}
